package br.com.serctam.session;

import javax.ejb.Remove;
import javax.ejb.Stateful;

import org.hibernate.Criteria;
import org.hibernate.Query;
import org.hibernate.criterion.Restrictions;
import org.jboss.seam.ScopeType;
import org.jboss.seam.annotations.AutoCreate;
import org.jboss.seam.annotations.Begin;
import org.jboss.seam.annotations.End;
import org.jboss.seam.annotations.In;
import org.jboss.seam.annotations.Logger;
import org.jboss.seam.annotations.Name;
import org.jboss.seam.annotations.Out;
import org.jboss.seam.annotations.Scope;
import org.jboss.seam.annotations.Synchronized;
import org.jboss.seam.annotations.Transactional;
import org.jboss.seam.international.StatusMessages;
import org.jboss.seam.log.Log;
import org.jboss.seam.persistence.HibernateSessionProxy;

import br.com.serctam.entity.Candidato;
import br.com.serctam.entity.Cargo;
import br.com.serctam.entity.NumeroInscrisao;
import br.com.serctam.entity.NumeroPreInscrisao;

@Synchronized
@Scope(ScopeType.APPLICATION)
@Stateful
@Name("geradorNumeroInscricao")
@AutoCreate
public class GerardorNumeroInscricaoBean implements GeradorNumeroInscricao
{
    @Logger private Log log;
    
    @In
    private HibernateSessionProxy hibernateSession;
    

    public Integer nextVal(Cargo cargo){
    	
    	int proximo = geraSequencial(cargo.getId());
    	atualizaProximoNumeroPreInscrisao(cargo, proximo);
    	return proximo;
    	
    }

    private void atualizaProximoNumeroPreInscrisao(Cargo cargo, Integer novoNumero){
    	
    	if(novoNumero == 1){
    		NumeroInscrisao ni = new NumeroInscrisao();
    		ni.setCargo(cargo);
    		ni.setUltimoNumero(1);
    		hibernateSession.persist(ni);
    	} else {
    		Query query = hibernateSession.getNamedQuery("atualizaUltimoNumeroInscrisao"); 
    		query.setLong("idCargo", cargo.getId());
    		query.setInteger("ultimo", novoNumero);
    		int qt = query.executeUpdate();
    		log.info("atualizaProximoNumeroInscrisao tuplas afetadas" + qt);
    		
    	}
    	
    	log.info("Numero inscrisao atualizado para " + novoNumero);
    	
    }

    
    private int geraSequencial(Long cargoId){
    	
        	
        	Query query = hibernateSession.getNamedQuery("buscaUltimoNumeroInscrisao"); 
        	query.setLong("idCargo", cargoId);
        	
        	Object oResult = query.uniqueResult();
        	
        	if(oResult == null){
        		return 1;
        	} else {
        		Integer ultimo = Integer.parseInt(oResult.toString());
        		ultimo++;
        		return ultimo;
        	}
        	
    }

    // add additional action methods


    @Remove
    public void destroy() {}



}